//
//  TTAddressManagerViewController.m
//  TaoTuo
//
//  Created by 周晨晔 on 2019/9/21.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTAddressManagerViewController.h"
#import "TTManagerAddressViewCell.h"
#import "TTAddNewAddressViewController.h"
#import "TTAddressModel.h"

#define bottomViewH 45

static NSString *cellID = @"address_cellID";

@interface TTAddressManagerViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, assign) NSInteger page;

@end

@implementation TTAddressManagerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"管理地址";
    @weakify(self)
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self)
        self.page = 1;
        [self getAddressListData];
    }];
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        @strongify(self)
        self.page++;
        [self getAddressListData];
    }];
    [self addBottomView];
    
    // 添加新地址之后
    [[TTLoginSingle sharedSingle].addAddressSuccessSubject subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        [self.tableView.mj_header beginRefreshing];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TTManagerAddressViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    [cell setModel:self.dataArray[indexPath.row] isFactory:NO];
    @weakify(self)
    cell.deleteAddressBlock = ^(TTManagerAddressViewCell * _Nonnull currentCell) {
        @strongify(self)
        NSIndexPath *ip = [self.tableView indexPathForCell:currentCell];
        [self.dataArray removeObjectAtIndex:ip.row];
        if (self.dataArray.count == 0) {
            [self.tableView reloadData];
        } else {
            [self.tableView deleteRowAtIndexPath:ip withRowAnimation:UITableViewRowAnimationFade];
        }
    };
    cell.setDefaultAddressBlock = ^(TTAddressModel * _Nonnull model) {
        @strongify(self)
        for (TTAddressModel *am in self.dataArray) {
            if (am.IsDefault) {
                am.IsDefault = NO;
                break;
            }
        }
        [self.tableView reloadData];
    };
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    @weakify(self)
    return [tableView fd_heightForCellWithIdentifier:cellID cacheByIndexPath:indexPath configuration:^(TTManagerAddressViewCell *cell) {
        @strongify(self)
        [cell setModel:self.dataArray[indexPath.row] isFactory:NO];
    }];
}

// 获取地址列表
- (void)getAddressListData
{
    NSDictionary *dic = @{
                          @"param.pageIndex" : @(self.page),
                          @"param.pageSize" : @(10)
                          };
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getAddressList_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if (self.page == 1) {
            [self.dataArray removeAllObjects];
        }
        
        NSArray *arr = responseObject;
        for (NSDictionary *dic in arr) {
            TTAddressModel *model = [TTAddressModel modelWithJSON:dic];
            [self.dataArray addObject:model];
        }
        
        [self.tableView.mj_header endRefreshing];
        
        if (arr.count < 10) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
        
        [self.tableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
        
    } showLoadingInView:self.view];
}

// 添加新地址
- (void)addNewAddress
{
    TTAddNewAddressViewController *newVC = [[TTAddNewAddressViewController alloc] init];
    [self.navigationController pushViewController:newVC animated:YES];
}

- (void)addBottomView
{
    UIButton *bottomBtn = [UIButton createButtonWithTitle:@"添加新地址" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:UIColorHex(673AB7) target:self action:@selector(addNewAddress)];
    bottomBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 0, Tabbar_Bottom_height, 0);
    [self.view addSubview:bottomBtn];
    [bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(bottomViewH + Tabbar_Bottom_height);
    }];
    
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.tableFooterView = [UIView new];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.emptyImageName = @"nodata";
        _tableView.emptyTitel = @"暂无地址";
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TTManagerAddressViewCell class]) bundle:nil] forCellReuseIdentifier:cellID];
        [self.view addSubview:_tableView];
        
        [_tableView mas_makeConstraints:^(MASConstraintMaker *make) { make.top.mas_equalTo(self.mas_topLayoutGuideTop);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(-bottomViewH);
        }];
    }
    return _tableView;
}



- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}



@end
